<template>
	<view class="container">
 			<view style="background-color: #fff;z-index:99;position:fixed;top:0;left:0;right:0;height:52px;">
				<uni-search-bar ref="searchBar"
				 radius="100" v-model="searchText" 
				  :focus="focus"
					placeholder="请输入搜索关键词" 
					clearButton="auto" 
					cancelButton="always" 
					@confirm="confirm" @cancel="cancel" />
			</view>
			<view style="height:52px;"></view>

		<view class="search-body" v-if="searchText.length<=1">	
			<!-- 搜索历史 -->
			<view class="word-container" v-if="localSearchList.length">
				<view class="word-container_header">
					<text class="word-container_header-text">搜索历史</text>
					<uni-icons v-if="!localSearchListDel" @click="localSearchListDel = true" class="search-icons"
						style="padding-right: 0;" :color="iconColor" size="18" type="trash"></uni-icons>
					<view v-else class="flex-center flex-row" style="font-weight:500;justify-content:space-between;">
						<text class="history-button" style="color: #666;" @click="LocalSearchListClear">全部删除</text>
						<text class="history-button" style="color: #c0402b;"
							@click="localSearchListDel = false">完成</text>
					</view>
				</view>
				<view class="word-container_body">
					<view class="flex-center flex-row word-container_body-text"
					 v-for="(word,index) in localSearchList"
						:key="index" @click="LocalSearchlistItemClick(word,index)">
						<text class="word-display" :key="word">{{word}}</text>
						<uni-icons v-if="localSearchListDel" size="12" type="closeempty" />
					</view>
				</view>
			</view>
			<!-- 搜索发现 -->
			<view class="word-container">
				<view class="word-container_header">
					<view class="flex-center flex-row">
						<text class="word-container_header-text">搜索发现</text>
						<uni-icons v-if="!netHotListIsHide" class="search-icons" :color="iconColor" size="14"
							type="reload" @click="searchHotRefresh"></uni-icons>
					</view>
					<uni-icons class="search-icons" style="padding-right: 0;" :color="iconColor" size="18"
						:type="netHotListIsHide ? 'eye-slash' : 'eye'"
						@click="netHotListIsHide = !netHotListIsHide"></uni-icons>
				</view>

				<unicloud-db ref="udb" v-slot:default="{data, loading, error, options}" 
				field="content"	collection="opendb-search-hot" 
					:distinct="true" orderby="create_date desc,count desc"
					page-data="replace" :page-size="10">
					<text v-if="loading && !netHotListIsHide" 
					class="word-container_body-info">正在加载...</text>
					<view v-else class="word-container_body">
						<template v-if="!netHotListIsHide">
							<text v-if="error" class="word-container_body-info">{{error.message}}</text>
							<template v-else>
								<text v-for="(word,index) in data" class="word-container_body-text" :key="index"
									@click="search(word.content)">{{word.content}}</text>
							</template>
						</template>
						<view v-else style="flex:1;">
							<text class="word-container_body-info">当前搜索发现已隐藏</text>
						</view>
					</view>
				</unicloud-db>
			</view>
		</view>
		<!-- 搜索联想 -->
		<view v-if="searchText.length>=2">
			<unicloud-db ref="sch_udb" 
			v-slot:default="{data, pagination, loading, hasMore, error, options}"
				:collection="compCollection" :page-size="20" getcount>
				<view v-if="error">{{error.message}}</view>
				<view v-else class="search-associative">
					<uni-list>
						<template v-for="(item,index) in data" :key="index">
							<uni-list-item direction="column" 
							:to="`./detail?id=${item._id}`">
								<!-- 通过header插槽定义列表的标题 -->
								<template v-slot:header>
									<view class="uni-title">{{item.behavior}}</view>
								</template>
								<!-- 通过body插槽定义列表内容显示 -->
								<template v-slot:body>
									<!-- <view class="uni-list-box"> -->
									<view class="uni-content">
										<view class="uni-title-sub u-line-5">{{item.excerpt}}</view>
									</view>
									<!-- </view> -->
								</template>
								<!-- 同步footer插槽定义列表底部的显示效果 -->
								<template v-slot:footer>
									<view class="uni-footer">
										<text class="uni-footer-text">【{{item.category[0].name}}】</text>
									<uni-dateformat class="uni-footer-text"
									 :date="item.create_date"
									 format="yyyy-MM-dd" :threshold="[60000, 3600000]">
									</uni-dateformat>
									</view>
								</template>
							</uni-list-item>

							<!-- <uni-list-item v-for="(item,index) in data" :key="item._id" 
					:ellipsis="1" :title="item.title" :note="item.excerpt"
					@click="associativeClick(item)" show-extra-icon
						 clickable :extra-icon="{size:18,color:iconColor,type:'search'}" /> -->

						</template>
					</uni-list>
					<uni-load-more :contentText="loadMore" :showText="false"
					:status="loading?'loading':(hasMore ? 'more' : 'noMore')"></uni-load-more>
					<!-- <view style="height: 80px;"></view> -->
					<u-safe-bottom></u-safe-bottom>
				</view>
				
				
			</unicloud-db>
			
		</view>
		
	</view>
</template>

<script>
	//import {parseImageUrl} from '@/common/cloud/parse-image-url.js';
	import { throttle } from '@/uni_modules/uview-plus';
	const T1 = 'xasa-behavior';
	const T2 = 'xasa-categories';
	const T3 = 'xasa-index-menus';
	const SearchField = 'behavior,violation,penalty,content'; // 联想时，搜索框值检索数据库字段名

	const searchLogDbName = 'opendb-search-log'; // 搜索记录数据库
	const ExampleField = "category,behavior,create_date";
	const OrderBy='last_modify_date desc';
	const db = uniCloud.databaseForJQL();


	const localSearchListKey = '__local_search_history'; //	本地历史存储字段名

	// 数组去重
	const arrUnique = arr => {
		for (let i = arr.length - 1; i >= 0; i--) {
			const curIndex = arr.indexOf(arr[i]);
			const lastIndex = arr.lastIndexOf(arr[i])
			curIndex != lastIndex && arr.splice(lastIndex, 1)
		}
		return arr
	};
	// 节流
	// 防抖
	/**
	 * 
	 * @param {要执行的函数} fn 
	 * @param {在操作多长时间后可再执行，第一次立即执行} interval 
	 */
/* 	function debounce(fn, interval, isFirstAutoRun) {
		var _self = fn;
		var timer = null;
		var first = true;

		if (isFirstAutoRun) {
			_self();
		}

		return function() {
			var args = arguments;
			var _me = this;
			if (first) {
				first = false;
				_self.apply(_me, args);
			}

			if (timer) {
				clearTimeout(timer)
				// return false;
			}

			timer = setTimeout(function() {
				clearTimeout(timer);
				timer = null;
				_self.apply(_me, args);
			}, interval || 200);
		}
	} */

	export default {
		data() {
			return {
				localSearchList: uni.getStorageSync(localSearchListKey),
				localSearchListDel: false,
				netHotListIsHide: false,
				searchText: '',
				iconColor: '#999999',
				//associativeList: [],
				//searchCollection: [],
				keyBoardPopup: false,

				hotWorld: '', //搜索热词，如果没有输入即回车，则搜索热词，但是不会加入搜索记录
				focus: true,
				loadMore:{
					contentdown: '',
					contentrefresh: "正在加载...",
					contentnomore: ''
				}
			}
		},
		created() {
			// #ifdef APP-PLUS
			uni.onKeyboardHeightChange((res) => {
				this.keyBoardPopup = res.height !== 0;
			})
			// #endif
			//this.searchText = getApp().globalData.searchText;
		},

		onPullDownRefresh(){
			this.$refs.sch_udb.loadData({
				clear: true
			}, () => {
				uni.stopPullDownRefresh()
			})
		},
		onReachBottom(){
			this.$refs.sch_udb.loadMore()
		},
		
		methods: {
/* 			async onListLoad(data, ended, pagination) {
				const listData = data
				// 处理cloud://文件链接
				for (let item of listData) {
					const imgs = await parseImageUrl(item.thumbnail)
					if (imgs != null) {
						item.thumbnail = imgs.map(x => x.src)
					}
					item.viewmode = item.viewmode || 0;
				}

				if (pagination.current == 1) {
					//articleList.value = data;
				} else {
					//articleList.value.concat(data)
				}
			}, */
			/* clear(res) {
			}, */
			throttle,
			confirm(res) {
				this.search(res.value);
			},
			cancel(res) {
				uni.hideKeyboard();
				this.searchText = '';
				uni.navigateBack();
				//this.loadList();
			},
			search(value){
				throttle(this.search_1(value),500)
			},
			search_1(value) {				
				if (!value && !this.hotWorld) {
					return;
				}
				if (value) {
					if (this.searchText !== value) {
						this.searchText = value
					}
					this.localSearchListManage(value);
					this.searchLogDbAdd(value)
				} else if (this.hotWorld) {
					this.searchText = this.hotWorld
				}
				uni.hideKeyboard();
				//this.loadList(this.searchText);
			},
			localSearchListManage(word) {
				let list = uni.getStorageSync(localSearchListKey);
				if (list.length) {
					this.localSearchList.unshift(word);
					arrUnique(this.localSearchList);
					if (this.localSearchList.length > 10) {
						this.localSearchList.pop();
					}
				} else {
					this.localSearchList = [word];
				}
				uni.setStorageSync(localSearchListKey, this.localSearchList);
			},
			LocalSearchListClear() {
				uni.showModal({
					content: '确认清空搜索历史吗？',
					confirmText: '删除',
					confirmColor: 'red',
					cancelColor: '#808080',
					success: res => {
						if (res.confirm) {
							this.localSearchListDel = false;
							this.localSearchList = [];
							uni.removeStorageSync(localSearchListKey)
						}
					}
				});
			},
			LocalSearchlistItemClick(word, index) {
				if (this.localSearchListDel) {
					this.localSearchList.splice(index, 1);
					uni.setStorageSync(localSearchListKey, this.localSearchList);
					if (!this.localSearchList.length) {
						this.localSearchListDel = false;
					}
					return;
				}
				this.search(word);
			},
			searchHotRefresh() {
				this.$refs.udb.refresh();
			},
			searchLogDbAdd(value) {
				/*
					在此处存搜索记录，如果登录则需要存 user_id，若未登录则存device_id
				 */
				this.getDeviceId().then(device_id => {
					db.collection(searchLogDbName).add({
						// user_id: device_id,
						device_id,
						content: value,
						create_date: Date.now()
					})
				})
			},
			getDeviceId() {
				return new Promise((resolve, reject) => {
					const uniId = uni.getStorageSync('uni_id');
					if (!uniId) {
						// #ifdef APP-PLUS
						plus.device.getInfo({
							success: (deviceInfo) => {
								resolve(deviceInfo.uuid)
							},
							fail: () => {
								resolve(uni.getSystemInfoSync().system + '_' + Math.random().toString(
									36).substr(2))
							}
						});
						// #endif
						// #ifndef APP-PLUS
						resolve(uni.getSystemInfoSync().system + '_' + Math.random().toString(36).substr(2))
						// #endif
					} else {
						resolve(uniId)
					}
				})
			},
/* 			associativeClick(item) {				
				this.loadList(item.name);
			}, */
/* 			loadList(text = '') {
				getApp().globalData.searchText = text;
				//uni.navigateBack()
			} */
		},
		computed: {
			/* associativeShow() {
				return this.searchText && this.associativeList.length;
			}, */
			compCollection() {
					const reg = new RegExp(this.searchText, 'i');
					const fds = SearchField.split(",");
					let regs = fds.map((v, i) => `${reg}.test(${v})`);
					let w = `${regs.join("||")}`;

					return [
						db.collection(T1).where(w).field(ExampleField).orderBy(OrderBy).getTemp(),
						db.collection(T2).field('_id,name').getTemp()
					]
			}
		},
		watch: {
			/* searchText: debounce(function(value) {
				if (value && value.length>=2) {
					const reg = new RegExp(value, 'i');
					let regs = SearchField.split(',').map((v,i)=>`${reg}.test(${v})`);
					
					db.collection(T1)
					.where(regs.join('||'))
					.field(ExampleField)
					.get({getCount:true}).then(res => {
						this.associativeList = res.data;						
					})
				} else {
					this.associativeList.length = 0;
					getApp().globalData.searchText = '';
				}
			}, 500) */
		}
	}
</script>

<style>
	/* #ifndef APP-NVUE */
	page {
		height: 100%;
		/* flex: 1; */
	}
	/* #endif */
</style>

<style lang="scss" scoped>
	@import '@/common/css/uni-ui.scss';

	$search-bar-height: 52px;
	$word-container_header-height: 72rpx;

	.history-button {
		font-size: 22rpx;
		padding-top: 4rpx;
		padding-bottom: 4rpx;
		padding-right: 20rpx;
	}

	.container {
		/* #ifndef APP-NVUE */
		/* height: 100%; */
		/* #endif */
		/* flex: 1; */
		background-color: #f7f7f7;
	}

	.search-body {
		background-color: #fff;
		border-bottom-right-radius: 10px;
		border-bottom-left-radius: 10px;
	}

	@mixin uni-flex {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
	}

	@mixin words-display {
		font-size: 26rpx;
		color: #666;
	}

	.flex-center {
		@include uni-flex;
		justify-content: center;
		align-items: center;
	}

	.flex-row {
		@include uni-flex;
		flex-direction: row;
	}

	/* #ifdef APP-PLUS */
	/* #ifndef APP-NVUE */
	::v-deep

	/* #endif */
	.uni-searchbar {
		padding-left: 0;
	}

	/* #endif */

	/* #ifndef APP-NVUE */
	::v-deep

	/* #endif */
	.uni-searchbar__box {
		border-width: 0;
	}

	/* #ifndef APP-NVUE */
	::v-deep

	/* #endif */
	.uni-input-placeholder {
		font-size: 28rpx;
	}

	.search-container {
		height: $search-bar-height;
		@include uni-flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: relative;
		background-color: #fff;

		@at-root {
			#{&}-bar {
				@include uni-flex;
				flex-direction: row;
				justify-content: center;
				align-items: center;
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
			}
		}
	}

	.search-associative {
		/* #ifndef APP-NVUE */
		/* overflow-y: auto; */
		/* #endif */
		position: absolute;
		top: $search-bar-height;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #fff;
		margin-top: 10rpx;
		padding-left: 10rpx;
		padding-right: 10rpx;
	}

	.search-icons {
		padding: 16rpx;
	}

	.word-display {
		@include words-display;
	}

	.word-container {
		padding: 20rpx;

		@at-root {
			#{&}_header {
				@include uni-flex;
				height: $word-container_header-height;
				line-height: $word-container_header-height;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;

				@at-root {
					#{&}-text {
						color: #3e3e3e;
						font-size: 30rpx;
						font-weight: bold;
					}
				}
			}

			#{&}_body {
				@include uni-flex;
				flex-wrap: wrap;
				flex-direction: row;

				@at-root {
					#{&}-text {
						@include uni-flex;
						@include words-display;
						justify-content: center;
						align-items: center;
						background-color: #f6f6f6;
						padding: 10rpx 20rpx;
						margin: 20rpx 30rpx 0 0;
						border-radius: 30rpx;
						/* #ifndef APP-NVUE */
						box-sizing: border-box;
						/* #endif */
						text-align: center;
					}

					#{&}-info {
						/* #ifndef APP-NVUE */
						display: block;
						/* #endif */
						flex: 1;
						text-align: center;
						font-size: 26rpx;
						color: #808080;
						margin-top: 20rpx;
					}
				}
			}
		}
	}
</style>